<template>
    <div class="flex flex-col gap-2 p-8">
        <div class="flex flex-row justify-between items-center mb-4">
            <div class="text-lg font-semibold text-black-100">新增
                <span class="text-sm">借阅记录</span>
            </div>
        </div>
        <n-form class="bg-gray-50 p-8 rounded-lg" ref="formRef" :label-width="80" :model="formValue" :rules="rules"
            size="small">
            <n-form-item label="书籍" path="book_id">
                <n-select v-model:value="formValue.book_id" placeholder="选择书籍"  :options="books" label-field="name" value-field="id"/>
            </n-form-item>
            <n-form-item label="用户" path="user_id">
                <n-select v-model:value="formValue.user_id" placeholder="选择用户"  :options="users" label-field="name" value-field="id"/>
            </n-form-item>
            <n-form-item label="应还日期" path="should_return_date">
                <n-date-picker v-model:value="formValue.should_return_date" type="date"  placeholder="应还日期" />
            </n-form-item>
            <n-form-item>
                <n-button attr-type="button" @click="handleValidateClick">
                    借阅
                </n-button>
            </n-form-item>
        </n-form>
    </div>

</template>

<script setup>

import { defineComponent, ref, onMounted } from "vue";
import { CreateLoan, GetUsers, GetBooks } from "../../wailsjs/go/main/App.js"
import { useMessage } from "naive-ui";
import { useRouter } from "vue-router";
const router = useRouter();
const message = useMessage();
const users = ref([]);
const books = ref([]);
const formRef = ref();
// 获取当前时间戳
const formValue = ref({
    book_id: "",
    user_id: "",
    should_return_date: new Date().getTime(),
})
const rules = {
    user_id: {
        required: true,
        message: "请选择用户",
    },
    book_id: {
        required: true,
        message: "请选择书籍",
    },
    should_return_date: {
        required: true,
        message: "选择应还日期",
    }
}

const handleValidateClick = (e) => {
    e.preventDefault();
    formRef.value?.validate((errors) => {
        if (!errors) {
            console.log(formValue.value);
            CreateLoan(formValue.value.user_id, formValue.value.book_id, formValue.value.should_return_date).then(res => {
                router.push({name: "loans"})
            })
        } else {
            console.log(errors);
            message.error("Invalid");
        }
    });
}

onMounted(() => {
    GetUsers().then(res => {
        console.log(res);
        users.value = res;
    })
    GetBooks("", "", 0, true).then(res => {
        books.value = res
    })
})

</script>